﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DongleTest
{
    public class Log
    {
        /// <summary>
        /// 写入测试log
        /// </summary>
        /// <param name="log"></param>
         public static void Write(string log)
        {
            string fileName;
            string exeFileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            string filePath = exeFileName.Substring(0, exeFileName.LastIndexOf('\\') + 1);
            string now = DateTime.Now.ToString("yyyyMMdd");

            if (!Directory.Exists(filePath + "Log\\"))
            {

                Directory.CreateDirectory(filePath + "Log\\");

            }

            fileName = filePath +"Log\\"+ now + ".csv";
            FileStream fs = null;

            bool isNew = false;
            if (System.IO.File.Exists(fileName))
            {
                fs = new FileStream(fileName, FileMode.Append);
            }
            else
            {
                fs = new FileStream(fileName, FileMode.CreateNew);
                isNew = true;
            }

            StreamWriter sw = new StreamWriter(fs,Encoding.UTF8);
            try
            {
                if (isNew)
                {
                    sw.WriteLine("测试种类,设备物理地址,测试时间,测试结果(传感器),测试结果(PCBA),测试结果(EEPROM),测试结果(波形),备注");
                }
                Console.WriteLine(log);
                sw.WriteLine(log);
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {
                if (isNew)
                {
                    System.IO.File.Delete(fileName);
                }
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }

    }
}
